<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
    $('#maxx').datetimepicker({
        format: "YYYY-MM-DD "
    })
    ;$('#minx').datetimepicker({
        format: "YYYY-MM-DD "

    });
	$('#tmsWaybillTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',

               //类型json
               dataType: "json",
        height:600,
        showFooter: true,//必须
        onPostBody:function () {
            //合并页脚
            merge_footer();
        },
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       // detailView: true,
    	       // 	//显示详细内容函数
	           // detailFormatter: "detailFormatter",
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/tms/tmsWaybill/data2",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	edit(row.id);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该运单记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/tms/tmsWaybill/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#tmsWaybillTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
               columns: [

                    {
                       field: 'projectName',
                       title: '项目',
                       sortable: true
                        ,
                        footerFormatter: function (value) {
                            var count = 0;
                            var co=0;
                            var kp=0;
                            var mlr=0;
                            for (var i=0; i<value.length;i++) {
                                count += parseInt(value[i].zjs);
                                co += parseInt(value[i].weight);
                                kp+=parseInt(value[i].zfy);
                                mlr+=parseInt(value[i].rentingCost);

                            }

                            var ce=mlr/kp;

                            return "筛选合计：  总件数："+ count+";总毛重："+co+";总费用："+kp+";总租车费用："+mlr+";租车费用比例："+toPercent(ce);
                        }
                   },{
                       field: 'guidance',
                       title: '现场督导',
                       sortable: true
                       ,formatter:function(value, row , index){
                           return value.name;
                       }
                   }
                   ,{
                       field: 'dispatchName',
                       title: '调度人员',
                       sortable: true
                       ,formatter:function(value, row , index){
                           return value.name;
                       }
                   }
                   ,{
                       field: 'date',
                       title: '下单日期',
                       sortable: true

                   }
                   ,{
                       field: 'fhrq',
                       title: '发货日期',
                       sortable: true

                   }
                   ,{
                       field: 'type',
                       title: '订单类型',
                       sortable: true

                   },{
                       field: 'workType',
                       title: '作业类型',
                       sortable: true

                   }
                   ,{
                       field: 'th',
                       title: '提货单号',
                       sortable: true

                   }
                   ,{
                       field: 'shipmentNumbers',
                       title: '装运单号',
                       sortable: true

                   }

                   ,{
		        field: 'code',
		        title: '合同号',
		        sortable: true

		    }

			,{
		        field: 'forwardingPrice',
		        title: '租车协议号',
		        sortable: true
		       
		    },{
                       field: 'contractDistance',
                       title: '起运地',
                       sortable: true

                   },{
                       field: 'arriveProvince',
                       title: '到站省',
                       sortable: true

                   },{
                       field: 'arrive',
                       title: '结算地',
                       sortable: true

                   },{
                       field: 'distance',
                       title: '合同里程',
                       sortable: true

                   } ,{
                       field: 'zjs',
                       title: '总件数',
                       sortable: true

                   } ,{
                       field: 'weight',
                       title: '总毛重',
                       sortable: true

                   }

                   ,{
                       field: 'ysdj',
                       title: '运输单价',
                       sortable: true

                   }
                   ,{
                       field: 'zfy',
                       title: '总费用',
                       sortable: true

                   }

                   ,{
                       field: 'freight',
                       title: '总车款',
                       sortable: true

                       }
                   ,{
                       field: 'totalCost',
                       title: '合同费用',
                       sortable: true

                   }
			,{
		        field: 'paymentNumber',
		        title: '预付现金',
		        sortable: true

		    }

			,{
		        field: 'loadingJe',
		        title: '预付油卡',
		        sortable: true

		    }
			,{
		        field: 'kdPayment',
		        title: '货到合同金额',
		        sortable: true
		       
		    }
			,{
		        field: 'receiptCalculate',
		        title: '回执合同金额',
		        sortable: true
		       
		    }
			,{
		        field: 'rentingCost',
		        title: '租车费用',
		        sortable: true
		       
		    }

			,{
		        field: 'fhpzc',
		        title: '防护品支出',
		        sortable: true
		       
		    }

			,{
		        field: 'zxfzc',
		        title: '装卸费支出',
		        sortable: true
		       
		    }

			,{
		        field: 'qtzc',
		        title: '其他支出',
		        sortable: true
		       
		    }
                   ,{
                       field: 'zcfybl',
                       title: '租车费用比例',
                       sortable: true

                   }
                   ,{
                       field: 'unitName',
                       title: '收货单位名称',
                       sortable: true

                   }
                   ,{
                       field: 'site',
                       title: '收货单位地址',
                       sortable: true

                   }

                   ,{
                       field: 'qszt',
                       title: '签收状态',
                       sortable: true

                   }
                   ,{
                       field: 'qsr',
                       title: '签收人',
                       sortable: true

                   }
                   ,{
                       field: 'qsjs',
                       title: '签收件数',
                       sortable: true

                   }
                   ,{
                       field: 'fhpsr',
                       title: '防护品收入',
                       sortable: true

                   }

                   ,{
                       field: 'xxfsr',
                       title: '信息费收入',
                       sortable: true

                   }

                   ,{
                       field: 'bxfsr',
                       title: '保险费收入',
                       sortable: true

                   }

                   ,{
                       field: 'qtsr',
                       title: '其它收入',
                       sortable: true

                   }

                   ,{
                       field: 'commonCarrier',
                       title: '承运商',
                       sortable: true

                   }
                   ,{
                       field: 'contacts',
                       title: '承运商联系人',
                       sortable: true

                   }
                   ,{
                       field: 'plateNumber',
                       title: '车牌号',
                       sortable: true

                   }

                   ,{
                       field: 'vehicleType',
                       title: '车辆类型',
                       sortable: true

                   }
                   ,{
                       field: 'drivingLicense',
                       title: '行驶证号',
                       sortable: true

                   }
                   ,{
                       field: 'driverName',
                       title: '司机姓名',
                       sortable: true

                   }
                   ,{
                       field: 'driverPhone',
                       title: '司机电话',
                       sortable: true

                   }

                   ,{
                       field: 'driveNumber',
                       title: '身份证号',
                       sortable: true

                   }



		     ]
		
		});
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#tmsWaybillTable').bootstrapTable("toggleView");
		}
	  
	  $('#tmsWaybillTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#sgcl').prop('disabled',  $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
            $('#edit').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#add').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#kjlc').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#e').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#dayin').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#day').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#scht').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#qxht').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#cbqr').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);
          $('#bx').prop('disabled', $('#tmsWaybillTable').bootstrapTable('getSelections').length!=1);

          $('#del').prop('disabled', ! $('#tmsWaybillTable').bootstrapTable('getSelections').length);
        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/tms/tmsWaybill/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#tmsWaybillTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#tmsWaybillTable').bootstrapTable('refresh');
		});
		
		
	});
function getbx() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.bx
    });}
function bx() {
    if(getbx()!="未投保"){
        return;
    }

    $.ajax({
        url : "${ctx}/ap/policy/cx",
        success : function(data) {
            $("#bd").empty();
            $.each(JSON.parse(data), function (idx, item) {
                $("#bd").append("<option value='"+item.name+"'>"+item.name+"</option>");
            })
        },
        error : function(data){
            alert("操作失败!");
        }
    });

    $("#qyd").val(geqsd());
    $("#mdd").val(gedzd());
    $("#zl").val(gezl());
    $("#tb").modal("show");
}
function geqsd() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.contractDistance
    });}


function gedzd() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.arrive
    });}
function gezl() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.weight
    });}
function tb() {
    $("#tb").modal("hide");
    jp.get("${ctx}/tms/tmsWaybill/tb?bz="+$("#bz").val()+"&name="+$("#hw").val()+"&bd="+$("#bd").val()+"&je="+$("#gsje").val()+"&id=" + getIdSelections(), function(data){
        if(data.success){
            $('#tmsWaybillTable').bootstrapTable('refresh');
            jp.success("预投保成功");
        }else{
            jp.error(data.msg);
        }
    })
    $("#qyd").val("");
    $("#mdd").val("");
    $("#zl").val("");
    $("#gsje").val("")
}
function scht() {
    jp.confirm('确认要生成合同吗？', function(){
    var p=getstatusSelections();
    if(p=="已装车"){
        $.ajax({
            url:'${ctx}/tms/tmsWaybill/scht?i='+getIdSelections(),
            success:function (data) {
                $('#tmsWaybillTable').bootstrapTable('refresh');
                jp.success("生成合同成功");
            }
        })
	}else{
        jp.warning("订单不支持该操作，请检查后重试")
    }
    })
}

function qxht() {
    jp.confirm('确认要取消合同吗？', function(){
        var p=getstatusSelections();
        if(p=="已生成合同"||p=="在途"||p=="已签收"){
            $.ajax({
                url:'${ctx}/tms/tmsWaybill/qxht?i='+getIdSelections(),
                success:function (data) {
                	if(data=="error"){
                   jp.error("运费已经结算，不能取消合同")
					}else{
                        $('#tmsWaybillTable').bootstrapTable('refresh');
                        jp.success("合同取消成功");
					}

                }
            })
        }else{
        	jp.warning("订单不支持该操作，请检查后重试")
		}
    })
}
function merge_footer() {
    var footer_tbody = $('.fixed-table-footer table tbody');
    var footer_tr = footer_tbody.find('>tr');
    var footer_td = footer_tr.find('>td');
    var footer_td_1 = footer_td.eq(0);
    //第一列为:'平均分',第二列为平局分内容
    for(var i=1;i<footer_td.length;i++) {
        footer_td.eq(i).hide();
    }
    footer_td_1.attr('colspan', 3).show();
}
function cbqr() {
    var p=getstatusSelections();
	if(getcbqr()=="1"){
		return;
	}
	if(!(p=="已生成合同"||p=="在途"||p=="已签收")){
		return;
	}
    jp.confirm('确认要成本确认吗？', function(){

        if((p=="已生成合同"||p=="在途"||p=="已签收")&&getcbqr!="1"){
            $.ajax({
                url:'${ctx}/tms/tmsWaybill/cbqr?i='+getIdSelections(),
                success:function (data) {
                    $('#tmsWaybillTable').bootstrapTable('refresh');
                    jp.success("成本确认成功");
                }
            })
        }else{
            jp.warning("订单不支持该操作，请检查后重试")
        }
    })
}
function dayin(){
    var p=getstatusSelections();
    if(p=="已生成合同"||p=="在途"||p=="已签收"){
        jp.openDialogView('打印', "${ctx}/tms/tmsWaybill/dayin?ids=" + getIdSelections(),'800px', '800px');
    }

}
function day(){
    var p=getstatusSelections();
    if(p=="已生成合同"||p=="在途"||p=="已签收"){
        jp.openDialogView('打印', "${ctx}/tms/tmsWaybill/day?ids=" + getIdSelections(),'800px', '800px');
    }

}
function ckd() {
    var plan=getstatusSelections();
    var str=plan.toString().split(",");
    var bol=true;
    for(var i=0;i<str.length;i++){
        if(str[i]!="已配载"){
        	bol=false;
		}
	}
    if(bol){
        $.ajax({
            url:'${ctx}/tms/tmsWaybill/ckd?ids='+getIdSelections(),
            success:function (data) {
                $('#tmsWaybillTable').bootstrapTable('refresh');
                jp.success("生成出库单成功");
            }
        })

    }else{
        jp.warning("请全部选择状态为已配载的运单");
	}
}
  function getIdSelections() {
        return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function getcbqr() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.cbqr
    });
}

function toPercent(point){
    var str=Number(point*100).toFixed(2);
    str+="%";
    return str;
}
function getstatusSelections() {
    return $.map($("#tmsWaybillTable").bootstrapTable('getSelections'), function (row) {
        return row.billStatus
    });}
function zctx() {
    var id = getIdSelections();
    var status=getstatusSelections();
    if(status=="已配载"||status=="已出库"||status=="已装车"){
        jp.openDialog('装车填写', "${ctx}/tms/tmsWaybill/form2?i="+id,'1200px', '1200px', $('#tmsWaybillTable'));}
}
  function deleteAll(){

		jp.confirm('确认要删除该运单记录吗？', function(){
			jp.loading();  	
			jp.get("${ctx}/tms/tmsWaybill/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#tmsWaybillTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})
          	   
		})
  }
  function ztgz() {
      var id=getIdSelections();
      var status=getstatusSelections();
      if(status=="已生成合同"||status=="在途"){
      jp.openDialog('在途跟踪', "${ctx}/tms/tailAfter/form?i="+id,'1400px', '1000px', $('#tmsWaybillTable'));
  }}
  function hdqs() {
  	var id=getIdSelections();
      var status=getstatusSelections();
      if(status=="在途"||status=="已签收"){
      jp.openDialog('回单签收', "${ctx}/tms/receipt/form?i="+id,'1400px', '1000px', $('#tmsWaybillTable'));
  }}
  function sgcl() {
      var id=getIdSelections();
      jp.openDialog('质量事故处理', "${ctx}/tms/accident/form?i="+id,'1400px', '1000px', $('#tmsWaybillTable'));
  }
  function kjlc(){
      var status=getstatusSelections();
      if(status=="已生成合同"){
      var id=getIdSelections();
      jp.openDialog('在途跟踪', "${ctx}/tms/tailAfter/form1?i="+id,'1400px', '1000px', $('#tmsWaybillTable'));
  }}
  
  function edit(id){//没有权限时，不显示确定按钮
  	  if(id == undefined){
			id = getIdSelections();
		}
	   <shiro:hasPermission name="tms:tmsWaybill:edit">
	  jp.openDialogView('查看运单', "${ctx}/tms/tmsWaybill/form?id=" + id,'1400px', '1000px', $('#tmsWaybillTable'));
	   </shiro:hasPermission>
	  <shiro:lacksPermission name="tms:tmsWaybill:edit">
	  jp.openDialogView('查看运单', "${ctx}/tms/tmsWaybill/form?id=" + id,'1400px', '1000px', $('#tmsWaybillTable'));
	  </shiro:lacksPermission>
  }
  
  
  
  
		   
  function detailFormatter(index, row) {
	  var htmltpl =  $("#tmsWaybillChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/tms/tmsWaybill/detail?id="+row.id, function(tmsWaybill){
    	var tmsWaybillChild1RowIdx = 0, tmsWaybillChild1Tpl = $("#tmsWaybillChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  tmsWaybill.tmsMaterialsInformationList;
		for (var i=0; i<data1.length; i++){
			addRow('#tmsWaybillChild-'+row.id+'-1-List', tmsWaybillChild1RowIdx, tmsWaybillChild1Tpl, data1[i]);
			tmsWaybillChild1RowIdx = tmsWaybillChild1RowIdx + 1;
		}
				
    	var tmsWaybillChild2RowIdx = 0, tmsWaybillChild2Tpl = $("#tmsWaybillChild2Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data2 =  tmsWaybill.tmsAdditionalChargeList;
		for (var i=0; i<data2.length; i++){
			addRow('#tmsWaybillChild-'+row.id+'-2-List', tmsWaybillChild2RowIdx, tmsWaybillChild2Tpl, data2[i]);
			tmsWaybillChild2RowIdx = tmsWaybillChild2RowIdx + 1;
		}
				
      	  			
      })
     
        return html;
    }
  
	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}

			
</script>
<script type="text/template" id="tmsWaybillChildrenTpl">//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">运单物料信息</a></li>
				<li><a data-toggle="tab" href="#tab-{{idx}}-2" aria-expanded="true">运单附加费用</a></li>
		</ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-2" class="tab-pane fade ">
						<table class="ani table">
						<thead>
							<tr>
								<th>支出类型</th>
								<th>金额</th>
								<th>数量</th>
								<th>单价</th>
								<th>备注信息</th>
							</tr>
						</thead>
						<tbody id="tmsWaybillChild-{{idx}}-2-List">
						</tbody>
					</table>
				</div>
				<div id="tab-{{idx}}-1" class="tab-pane fade in active">
					<table class="ani table">
						<thead>
							<tr>
								<th>提货单号</th>
								<th>物料编码</th>
								<th>物料名称</th>
								<th>物料规格</th>
								<th>派车量</th>
								<th>装车量</th>
								<th>毛重</th>
								<th>体积</th>
								<th>提货仓库</th>
								<th>备注信息</th>
							</tr>
						</thead>
						<tbody id="tmsWaybillChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
	</script>
	<script type="text/template" id="tmsWaybillChild2Tpl">//<!--
				<tr>
					<td>
						{{row.balanceType}}
					</td>
					<td>
						{{row.money}}
					</td>
					<td>
						{{row.quantity}}
					</td>
					<td>
						{{row.unitPrice}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
	</script>
	<script type="text/template" id="tmsWaybillChild1Tpl">//<!--
				<tr>
					<td>
						{{row.number}}
					</td>
					<td>
						{{row.coding}}
					</td>
					<td>
						{{row.name.name}}
					</td>
					<td>
						{{row.specification}}
					</td>

					<td>
						{{row.vehicleQuantity}}
					</td>
					<td>
						{{row.loadingQuantity}}
					</td>
					<td>
						{{row.weight}}
					</td>
					<td>
						{{row.volume}}
					</td>
					<td>
						{{row.depot}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
	</script>
